package org.daidai.abstrusewriting.homepage.top.service;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.IBinder;
import android.util.Log;

import org.daidai.abstrusewriting.R;

import java.io.IOException;

public class PlayService extends Service {

    private MediaPlayer mediaPlayer;
    private String url;

    public PlayService() {

    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {

            url = intent.getStringExtra("url");
            if (url != null) {
                Uri parse = Uri.parse(url);
                mediaPlayer = MediaPlayer.create(this, parse);
            }

            String action = intent.getStringExtra("action");
            if ("play".equals(action)) {
                mediaPlayer.start();
            } else if ("stop".equals(action)) {
                mediaPlayer.pause();
            }

            Log.d("onStartCommand", "action: " + action + "    url:" + url);
        }

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
        }
        mediaPlayer.release();
        mediaPlayer = null;
        super.onDestroy();
    }
}
